﻿using System;
using System.Globalization;
using System.Windows.Data;
using DataLayer.Types;

namespace ViewModel.Aggregators
{
    /// <summary>
    /// Calculates the Savings plan allotment amount
    /// </summary>
    public class SavingsPlanAllotmentProvider : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                DateTime startTime = (DateTime)values[0];
                DateTime endTime = (DateTime)values[1];
                decimal targetAmount = (decimal)values[2];
                decimal initialAmount = (decimal)values[3];

                FrequencyItem frequencyItem = values[4] as FrequencyItem;   //period
                if (frequencyItem == null) return string.Empty;

                return SavingsPlanCalculator.CalculateAllotmentAmount(startTime, endTime, 
                                                              targetAmount, initialAmount, frequencyItem).ToString("C");
            }
            catch (InvalidCastException e)
            {
                log4net.LogManager.GetLogger(GetType()).Error("Could not convert properties to a decimals", e);
                return null;
            }
            catch (DivideByZeroException d1)
            {
                log4net.LogManager.GetLogger(GetType()).Error("Attempted to divide by zero. Possibly FrequencyItem value is zero", d1);
                return null;
            }
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
